package cn.boysoft.core.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.boysoft.core.model.Tree;
/**
 * @author 付厚俊
 * CreateTime 2013-4-5 上午10:29:52
 */
public class TreeUtil {

	public static Collection<? extends Tree> buildTree(Collection< ? extends Tree> collection){
		if(collection == null){
			return null;
		}
		Map<String, Tree> temp = new LinkedHashMap<String, Tree>();
		for (Tree target : collection) {
			temp.put(target.getId(), target);
		}
		List<Tree> result = new ArrayList<Tree>();
		for (Tree target : collection) {
			String id = target.getId();
			Tree tree = temp.get(id);
			String parentId = target.getParentId();
			if (parentId == null) {
				result.add(target);
				continue;
			} else {
				Tree parent = temp.get(parentId);
				if (parent != null) {
					List<Tree> children = parent.getChildren();
					if(children == null){
						children = new ArrayList<Tree>();
						parent.setChildren(children);
					}
					children.add(tree);
				}
			}
		}
		return result;
	}
}
